package com.foxzzz.datamemory.service;

import com.foxzzz.datamemory.entity.BlobSave;
import com.foxzzz.datamemory.repository.BlobSaveRepository;
import com.foxzzz.datamemory.util.BlobUtil;
import com.foxzzz.datamemory.util.SnowflakeUtil;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.util.*;

/**
 * @Author wujie
 * @Class BlobSaveService
 * @Description
 * @Date 2020/5/25 16:19
 */
@Service
public class BlobSaveService {
    @Autowired
    private BlobSaveRepository repository;
    @Autowired
    private BlobUtil util;
    @Autowired
    private EntityManager entityManager;

    public String upload(String name, InputStream inputStream) {
        BlobSave save = new BlobSave();
        save.setFileName(name);
        save.setBlobSaveId(SnowflakeUtil.getIdString());
        save.setDateCreate(new Date());
        save.setBlob(util.getBlob(inputStream));
        repository.save(save);
        return save.getBlobSaveId();
    }

    public BlobSave getById(String id) {
        if (id == null) {
            return null;
        }
        return repository.findById(id).orElseGet(null);
    }

    public List<BlobSave> list() {
        List<BlobSave> all = repository.findAll();
        all.forEach(a -> {
            a.setBlob(null);
        });
        return all;
    }

//    public String test() {
//        long start = System.currentTimeMillis();
//        entityManager = entityManager.getEntityManagerFactory().createEntityManager();
//        Session session = entityManager.unwrap(Session.class);
//        FileInputStream fileInputStream = null;
//        Blob blob = null;
//        try {
//            fileInputStream = new FileInputStream("C:\\Users\\Hex\\Desktop\\work\\1.csv");
//            System.out.println(fileInputStream.available());
//            blob = Hibernate.getLobCreator(session).createBlob(fileInputStream, fileInputStream.available());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        BlobSave blobSave = new BlobSave();
//        blobSave.setBlob(blob);
//        blobSave.setDateCreate(new Date());
//        blobSave.setFileName("1.csv");
//        blobSave.setBlobSaveId(UUID.randomUUID().toString());
//        System.out.println(System.currentTimeMillis() - start);
//        repository.save(blobSave);
//        System.out.println(System.currentTimeMillis() - start);
//        return blobSave.getBlobSaveId();
//    }


}
